package com.boyuan.aboutcase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.boyuan.huijiaoyu.MyFriendActivity;
import com.boyuan.huijiaoyu.R;
import com.boyuan.huijiaoyu.R.id;
import com.boyuan.huijiaoyu.R.layout;
import com.example.contactfragment.ContactGroupService;
import com.example.contactfragment.ContactService;
import com.example.newfragment.DetailPerson;
import com.example.newfragment.members;
import com.magicsoft.app.entity.CaseDetailEntity;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.CaseService;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class AddCaseMembersActivity extends Activity implements OnClickListener {

	private ArrayList<DetailPerson> friendlist = new ArrayList<DetailPerson>();
	private List<members> areadymemberslist = new ArrayList<members>();//已经关注的列表
	private ArrayList<String> areadynamelist = new ArrayList<String>();//已经关注人的名字列表
	private ArrayList<String> areadyphonelist = new ArrayList<String>();//已经关注人的电话列表
	private ArrayList<String> namelist = new ArrayList<String>();//好友名字列表
	private ArrayList<String> phonelist = new ArrayList<String>();//好友电话列表
	private ArrayList<String> addphonelist = new ArrayList<String>();//添加好友电话列表
	private ArrayList<DetailPerson> Addlist = new ArrayList<DetailPerson>();//添加关注的列表
	
	private ListView mListView;
	private String TAG = "AddCaseMembersActivity";
	private CaseService caseService;
	private CaseDetailEntity caseDetailEntity;
	private ContactService contactService;
	private ContactGroupService contactgroupService;
	private String id;
	private MyAdapter adapter;
	private String groupid;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_case_members);
		caseDetailEntity = (CaseDetailEntity) getIntent().getSerializableExtra(
				"caseDetailEntity");
		groupid = caseDetailEntity.getGid();
		areadymemberslist = caseDetailEntity.getMembers();
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		id = sp.getString("id", "");
		getMyFriendCache();
//		getFrequentContacts();
		initUI();
	}

	private void initUI() {
		for (int i = 0; i < friendlist.size(); i++) {
			for (int j = 0; j < areadymemberslist.size(); j++) {
				if(friendlist.get(i).getRealname().equals(areadymemberslist.get(j).getName())){
					areadyphonelist.add(friendlist.get(i).getMobile());
					areadynamelist.add(friendlist.get(i).getRealname());
				}
			}
		}
		findViewById(R.id.lay_back).setOnClickListener(this);
		findViewById(R.id.lay_save).setOnClickListener(this);

		mListView = (ListView) findViewById(R.id.listView1);
		adapter = new MyAdapter();
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				CheckBox cb = (CheckBox) arg1.findViewById(R.id.checkBox1);
				cb.toggle();
			}
		});
	}
	
	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return namelist.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			View inflate = getLayoutInflater().inflate(R.layout.list_friend, null);
			final TextView tv_name = (TextView) inflate.findViewById(R.id.tvname);
			final CheckBox cb = (CheckBox) inflate.findViewById(R.id.checkBox1);
			ImageView image = (ImageView) inflate.findViewById(R.id.imag_photo);
			tv_name.setText(namelist.get(arg0));
			imageLoader = ImageLoader.getInstance();
			options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.default_header)
			.showImageForEmptyUri(R.drawable.default_header)
			.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
			.cacheOnDisc(true).considerExifParams(true)
			.build();
			String uri = Constant.photourl1 + phonelist.get(arg0);
			imageLoader.displayImage(uri, image, options);
			if(areadynamelist.contains(tv_name.getText().toString().trim())){
				cb.setChecked(true);
			}
			
			cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
					if(areadynamelist.contains(tv_name.getText().toString().trim())){
						ischecked = true;
						cb.setChecked(true);
					}
					if(ischecked){
						if(areadynamelist.contains(tv_name.getText().toString().trim())){
							
						}else{
							addphonelist.add(phonelist.get(arg0));
							Addlist.add(friendlist.get(arg0));
						}
					}else{
						if(areadynamelist.contains(tv_name.getText().toString().trim())){
							
						}else{
							addphonelist.remove(phonelist.get(arg0));
							Addlist.remove(friendlist.get(arg0));
						}
					}
				}
			});
			return inflate;
		}
		
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lay_back:
			finish();
			break;
		case R.id.lay_save:
			AddMembers();
			break;

		default:
			break;
		}
	}

	// 获取我的好友缓存
	private void getMyFriendCache() {
		friendlist.clear();
		namelist.clear();
		phonelist.clear();
		ArrayList<DetailPerson> myfriendList = SharePreferenceHelper.getContactFrindList(AddCaseMembersActivity.this, id);
		if (myfriendList.size() > 0) {
			friendlist.addAll(myfriendList);
			for (int i = 0; i < friendlist.size(); i++) {
				namelist.add(friendlist.get(i).getRealname());
				phonelist.add(friendlist.get(i).getMobile());
			}
		}else{
			Toast.makeText(AddCaseMembersActivity.this, "您还没有好友！", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 获取常用联系人
	 */
	private void getFrequentContacts() {

		if (contactService == null) {
			contactService = new ContactService(this);
		}
		contactService.getFrequentContacts(id,
				new GetOneRecordListener<List<DetailPerson>>() {

					@Override
					public void onFinish(List<DetailPerson> data) {
						friendlist.clear();
						namelist.clear();
						phonelist.clear();
						if (data != null && data.size() > 0) {
							friendlist.addAll(data);
							SharePreferenceHelper.saveMyFrindList(AddCaseMembersActivity.this, id, data);
							for (int i = 0; i < friendlist.size(); i++) {
								namelist.add(friendlist.get(i).getRealname());
								phonelist.add(friendlist.get(i).getMobile());
							}

						} else {
							Toast.makeText(AddCaseMembersActivity.this, "您还没有好友！",
									Toast.LENGTH_SHORT).show();
							finish();
						}
						adapter.notifyDataSetChanged();
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(AddCaseMembersActivity.this, Message,
								false);
					}
				});
	}
	

	private void AddMembers() {
		if (Addlist.size() == 0) {
			ToastHelper.showMsg(this, "请选择要添加的成员", false);
			return;
		}

		if (caseService == null) {
			caseService = new CaseService(this);
		}
		String case_id = caseDetailEntity.getCid();
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		String id = sp.getString("accountId", "");
		String realname = sp.getString("realname", "");

		StringBuffer sb = new StringBuffer();

		sb.append("[");
		for (int i = 0; i < Addlist.size(); i++) {
			DetailPerson detailPerson = Addlist.get(i);
			String account_id = detailPerson.getAccount_id();
			String realname2 = detailPerson.getRealname();
			sb.append("{'id':" + "'" + account_id + "'" + ",'name':" + "'"
					+ realname2 + "'" + "},");
		}

		String members = sb.toString();
		int lastIndexOf = members.lastIndexOf(",");
		members = members.substring(0, lastIndexOf);
		members = members + "]";
		members = members.replaceAll("\'", "\"");
		final String addmembers = members;
		caseService.addCasesMembers("1", case_id, members, id, realname,
				new PostRecordResponseListener() {

					@Override
					public void onFinish(String succString) {
						Intent intent1 = new Intent();
						intent1.setAction(Constant.ADDMENBER);
						sendBroadcast(intent1);
						ToastHelper.showMsg(AddCaseMembersActivity.this, succString, false);
						Intent data = new Intent();
						data.putExtra("addmembers", addmembers);
						setResult(002, data );
						Intent intent = new Intent();
						setResult(222, intent);
						finish();
					}

					@Override
					public void onFailed(String failString) {
						ToastHelper.showMsg(AddCaseMembersActivity.this,
								failString, false);
					}
				});

	}
	
}
